package com.gyf.algorithm.struc.list;

public class LinkedList<E> extends AbsList<E> {

    private Node<E> first;

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public int indexOf(E e) {
        if (e == null) {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (node.element == null) {
                    return i;
                }
                node = node.next;
            }
        } else {
            Node<E> node = first;
            for (int i = 0; i < size; i++) {
                if (node.element.equals(e)) {
                    return i;
                }
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    @Override
    public void add(int index, E e) {
        if (index == 0) {
            first = new Node<>(e, first);
        } else {
            Node<E> previous = node(index - 1);
            previous.next = new Node<>(e, previous.next);
        }
        size++;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E e) {
        Node<E> node = node(index);
        E old = node.element;
        node.element = e;
        return old;
    }

    @Override
    public E remove(int index) {
        Node<E> delNode = first;
        if (index == 0) {
            first = first.next;
        } else {
            Node<E> previous = node(index - 1);
            delNode = previous.next;
            previous.next = previous.next.next;
        }
        size--;
        return delNode.element;
    }

    private Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

     static class Node<E> {
        E element;
        Node<E> next;

         Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }
}
